package com.informationsystem.model;

import com.informationsystem.model.BaseObject;

import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Indexed;
import org.hibernate.search.annotations.IndexedEmbedded;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;

import javax.xml.bind.annotation.XmlRootElement;

import java.io.Serializable;

@Entity
@Table(name="downloads")
@Indexed
@XmlRootElement
public class Downloads extends Information implements Serializable {
    private String filename;
    private Set<Tag> tags = new HashSet<Tag>(0);
    
    @Column(name="filename", nullable=false, length=1000)
    @Field
    public String getFilename() {
        return this.filename;
    }
    
    public void setFilename(String filename) {
        this.filename = filename;
    }
    
	@ManyToMany(cascade = {CascadeType.REFRESH, CascadeType.MERGE}, fetch=FetchType.EAGER)
	    @JoinTable(name="tag2downloads", joinColumns = { 
	        @JoinColumn(name="downloads_id", nullable=false, updatable=false) }, inverseJoinColumns = { 
	        @JoinColumn(name="tag_id", nullable=false, updatable=false) })
	@Fetch(value = FetchMode.SUBSELECT)
    public Set<Tag> getTags() {
        return this.tags;
    }
    
    public void setTags(Set<Tag> tags) {
        this.tags = tags;
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Downloads pojo = (Downloads) o;

        if (filename != null ? !filename.equals(pojo.filename) : pojo.filename != null) return false;

        return true;
    }

    public int hashCode() {
        int result = 0;
        result = (filename != null ? filename.hashCode() : 0);

        return result;
    }

    public String toString() {
        StringBuffer sb = new StringBuffer(getClass().getSimpleName());

        sb.append(" [");
        sb.append("id").append("='").append(getId()).append("', ");
        sb.append("filename").append("='").append(getFilename()).append("', ");
        
        sb.append("]");
      
        return sb.toString();
    }
    
    @Transient
    public String getDisplayTag(){
    	String tagstring = "";
    	for(Tag t : tags){
    		tagstring+="["+t.getTagname()+"]";
    	}
    	return tagstring;
    }
}
